package com.edu.controller;


import com.edu.domin.dto.UserInfoDTO;
import com.edu.domin.vo.ArticleVo;
import com.edu.domin.vo.UserInfoVo;
import com.edu.entity.User;
import com.edu.properties.MyUserDetails;
import com.edu.service.CommonService;
import com.edu.service.IArticleService;
import com.edu.service.ICategoryService;
import com.edu.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * <p>
 * 系统用户表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-05-15
 */
@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IUserService userService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private ICategoryService  categoryService;
    @RequestMapping("/login")
    public String login(){
        return "login";
    }
    @RequestMapping("/loginFail")
    public String loginFail(){
        return "loginFail";
    }
    @GetMapping("/index")
    public String index(Model model){
        List<ArticleVo> listeryone = articleService.listeryone();
        // 返回文章列表
        model.addAttribute("categories",categoryService.list());
        model.addAttribute("articles",listeryone);
        return "index";
    }

    /**
     * 根据分类筛选首页呈现文章
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/index/{id}")
    public String indexcategory(Model model,@PathVariable Long id){
        List<ArticleVo> listeryone = articleService.listeryByid(id);
        model.addAttribute("categories",categoryService.list());
        model.addAttribute("articles",listeryone);
        return "index";
    }

    /**
     * 注册
     * @return
     */

    @RequestMapping("/register")
    public String register(){
        return "register";
    }
    //注册功能
    @PostMapping("/register")
    public String register(@RequestParam String username, @RequestParam String password) {
        User user = new User();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password1 = encoder.encode(password);
        user.setUsername(username);
        user.setPassword(password1);
        user.setIsAdmin(0);
        userService.saveone(user);
        log.info("注册页面");
        return "login";
    }
    @GetMapping("/noauth")
    public String noauth(){
        return "noauth";
    }
    @GetMapping("/info")
    public String info(Model model, Authentication authentication) {
        // 从 Authentication 中获取 principal
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        Long id = userDetails.getId(); // 安全获取 id
       UserInfoVo vo = userService.getinfo(id);
       model.addAttribute("userInfo",vo);
        return "user-info";
    }
    //修改个人信息
    @GetMapping("/update")
    public String update( Model model, Authentication authentication) {
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        Long id = userDetails.getId();
        UserInfoVo getinfo = userService.getinfo(id);
        model.addAttribute("userInfo",getinfo);
        return "updateinfo";
    }
    @PostMapping("/update")
    @ResponseBody
    public String edit(Model model, Authentication authentication, @RequestParam("image") MultipartFile image, @RequestParam("username") String username, @RequestParam("email") String email, @RequestParam("phone") String phone, @RequestParam("address") String address) {
        log.info("用户信息：username={}, email={}, phone={}, address={}", username, email, phone, address);
        try {
            // 从 Authentication 中获取 principal
            MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
            Long id = userDetails.getId(); // 安全获取 id

            // 处理图片上传
            String imagePath = null;
            if (!image.isEmpty()) {
                imagePath = commonService.upload(image); // 调用 CommonService 的 upload 方法
                log.info("图片上传成功，路径: {}", imagePath);
            }

            // 构造 UserInfoDTO 对象
            UserInfoDTO userInfoDTO = new UserInfoDTO();
            userInfoDTO.setUsername(username);
            userInfoDTO.setEmail(email);
            userInfoDTO.setPhone(phone);
            userInfoDTO.setAddress(address);
            userInfoDTO.setImage(imagePath);

            // 更新用户信息
            userService.updateInfo(id, userInfoDTO);
            return "redirect:/user/info"; // 修改为重定向到用户信息页面
        } catch (Exception e) {
            log.error("更新用户信息失败: {}", e.getMessage(), e);
            return "redirect:/user/update?error=" + e.getMessage(); // 修改为重定向到更新页面并携带错误参数
        }
    }


}
